/*
 *  TCPFarfetchClient.c
 *  farfetchproject
 *
 *  Created by Rodrigo Souza on 4/18/10.
 *  Copyright 2010 Unicamp. All rights reserved.
 *
 */

#include "ClientProperties.h"
#include "TCPClientConnectionHandler.c"
#include "ClientDataHandler.c"

MoviesList* getTCPResponse(int sockfd, int *count, int option) {
	int answerSize = 0;
	char recvline[MAXLINE + 1];

	// Receive next message's size from server
	answerSize += read(sockfd, recvline, sizeof(int));
	recvline[answerSize] = '\0';
	int nxtMsgSize = 0;
	memcpy(&nxtMsgSize, recvline, sizeof(int));

	//print next message's size
// 	printf("answerSize: <%d>\nnxtMsgSize: <%d>\n", answerSize, nxtMsgSize);

	// Receive data message of server
	char* buffer = malloc((nxtMsgSize+1)*sizeof(char));
 	int n = read(sockfd, buffer, nxtMsgSize);
 	buffer[n] = '\0';
	
	//print received message
// 	printf("Recebi: recvline:<%s>\n", buffer);
	
	// Retrieve useful info from received data
 	MoviesList* list = getData(buffer, count, option);

	return list;
}


MoviesList* createConnection(Request* r, int *count) {
	int sockfd;
	struct sockaddr_in servaddr;
	
	bzero(&servaddr, sizeof(servaddr));					//	alocate memory with '0's
	servaddr.sin_family = AF_INET;						// 	set format address
	servaddr.sin_addr.s_addr = inet_addr(SERVER_IP);  	/* Server IP address */
	servaddr.sin_port   = htons(SERVER_PORT);			//	set port
	
	// Set client fields and create the connection
	sockfd = Socket(AF_INET, SOCK_STREAM, 0);
	InetPton(AF_INET, SERVER_IP, &servaddr.sin_addr);
	Connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
	
	// get socket info
	char* sockInfo = getClientInfo(sockfd, &servaddr);
		
	//printf("\n> Sending r->option = %d\n", r->option);
	
	// Send message to server
	int bytes = send(sockfd, r, REQUEST_SIZE, 0);
	
	//printf("\n> Waiting server answer...\n");
	
	return getTCPResponse(sockfd, count, r->option);
		
}

/* Creates the connection message that will be sent to the server. */
MoviesList* createTCPRequest(Request *r, int *count) {
	return createConnection(r, count);
}

/* Method called by the interface. Returns the required information. */
MoviesList* executeRequest(Request *r, int *count) {
	return createTCPRequest(r, count);
}
